package com.xiangyu.ai.config;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xiangyu.ai.domain.Order;
import com.xiangyu.ai.mapper.OrderMapper;
import com.xiangyu.ai.service.AiAssistant;
import com.xiangyu.ai.service.FunctionAssistant;
import com.xiangyu.ai.service.NumberExtractor;
import com.xiangyu.ai.service.UserExtractor;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.tool.ToolExecutor;
import dev.langchain4j.service.tool.ToolProvider;
import dev.langchain4j.service.tool.ToolProviderRequest;
import dev.langchain4j.service.tool.ToolProviderResult;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static dev.langchain4j.agent.tool.JsonSchemaProperty.description;
import static dev.langchain4j.agent.tool.JsonSchemaProperty.type;

/**
 * @author zxb
 * @version 1.0
 * @date 2025-02-22 10:38
 */
@Component
@Configuration(proxyBeanMethods = false)
public class LLMconfig {

    @Resource
    private OrderMapper orderMapper;


    /**
     * 语言
     * @return
     */
    @Bean
    public ChatLanguageModel chatLanguageModel() {
        return OpenAiChatModel.builder()
                .apiKey("sk-b88c50cdcfe74851968eba2b15fae072")  // 阿里云百炼的key
                .modelName("qwen-turbo")  // 模型名称
                .logRequests(true)   // 日志
                .logResponses(true)
                .maxRetries(1)  // 重试次数
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();
    }


    /**
     * 流式输出
     * @return
     */
    @Bean
    public StreamingChatLanguageModel streamingChatLanguageModel() {
        return OpenAiStreamingChatModel.builder()
                .apiKey("sk-b88c50cdcfe74851968eba2b15fae072")  // 阿里云百炼的key
                .modelName("qwen-turbo")  // 模型名称
                .logRequests(true)   // 日志
                .logResponses(true)
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();
    }


    /**
     * 记忆缓存
     * @param chatLanguageModel
     * @return
     */
    @Bean
    public AiAssistant aiAssistant(ChatLanguageModel chatLanguageModel) {
        AiAssistant aiAssistant = AiServices.builder(AiAssistant.class)
                .chatLanguageModel(chatLanguageModel)
                .chatMemoryProvider(MemoryId -> MessageWindowChatMemory.withMaxMessages(10))
                .build();
        return aiAssistant;

    }


//    @Bean
//    public FunctionAssistant functionAssistant(ChatLanguageModel chatLanguageModel) {
//        // 工具说明 ToolSpecification
//        ToolSpecification toolSpecification = ToolSpecification.builder()
//                .name("invoice_assistant")
//                .description("根据用户提交的开票信息，开具发票")
//                .addParameter("companyName", type("string"), description("公司名称"))
//                .addParameter("dutyNumber", type("string"), description("税号"))
//                .addParameter("amount", type("string"), description("金额,保留两位有效数字"))
//                .build();
//
//        // 业务逻辑 ToolExecutor
//        ToolExecutor toolExecutor = (toolExecutionRequest, memoryId) -> {
//            String arguments1 = toolExecutionRequest.arguments();
//            System.out.println("arguments1 =>>>> " + arguments1);
//            return "开具成功";
//        };
//
//        return AiServices.builder(FunctionAssistant.class)
//                .chatLanguageModel(chatLanguageModel)
//                .tools(Map.of(toolSpecification, toolExecutor))
//                .build();
//    }




    @Bean
    public FunctionAssistant functionAssistant(ChatLanguageModel chatLanguageModel) {
        return AiServices.builder(FunctionAssistant.class)
                .chatLanguageModel(chatLanguageModel)
                .toolProvider(new ToolProvider() {
                    // 动态工具配置
                    @Override
                    public ToolProviderResult provideTools(ToolProviderRequest request) {
                        // 客户的语言中包含哪些语句，则进入哪个工具
                        if (request.userMessage().singleText().contains("买书")) {
                            ToolSpecification toolSpecification = ToolSpecification.builder()
                                    .name("get_booking_details")
                                    .description("用户购买书籍")
                                    .addParameter("bookName", type("string"), description("书籍名称"))
                                    .addParameter("money", type("string"), description("价格，保留两位有效数字"))
                                    .build();

                            // 业务逻辑 ToolExecutor
                            ToolExecutor toolExecutor = (toolExecutionRequest, memoryId) -> {
                                String arguments1 = toolExecutionRequest.arguments();
                                System.out.println("arguments1 =>>>> " + arguments1);
                                return "购买成功，返回书籍信息";
                            };

                            return ToolProviderResult.builder()
                                    .add(toolSpecification, toolExecutor)
                                    .build();
                        }

                        if (request.userMessage().singleText().contains("购买")){
                            ToolSpecification toolSpecification = ToolSpecification.builder()
                                    .name("order_assistant")
                                    .description("根据用户提交的订单信息，下订单")
                                    .addParameter("comboName", type("string"), description("套餐名称"))
                                    .addParameter("comboAmount", type("string"), description("套餐金额,保留两位有效数字"))
                                    .addParameter("giftBagName", type("string"), description("礼包名称"))
                                    .addParameter("giftBagAmount", type("string"), description("礼包金额,保留两位有效数字"))
                                    .build();

                            // 业务逻辑 ToolExecutor
                            ToolExecutor toolExecutor = (toolExecutionRequest, memoryId) -> {
                                String arguments = toolExecutionRequest.arguments();
                                JsonElement jsonElement = JsonParser.parseString(arguments);
                                JsonObject jsonObject = jsonElement.getAsJsonObject();
                                String comboName = jsonObject.get("comboName").getAsString();
                                String comboAmount = jsonObject.get("comboAmount").getAsString();
//                                String giftBagName = jsonObject.get("giftBagName").getAsString();
//                                String giftBagAmount = jsonObject.get("giftBagAmount").getAsString();

                                List<String> orderIds = new ArrayList<>();

                                if (!StringUtil.isEmpty(comboName) && !StringUtil.isEmpty(comboAmount)) {
                                    Order order = new Order();
                                    order.setOrderId("4654548453468");
                                    order.setMoney(Double.valueOf(comboAmount));
                                    order.setUserMobel("19117681548");
                                    order.setPayOrderId("fsd5fgsd54gds556");
                                    order.setName(comboName);
                                    orderMapper.add(order);
                                    orderIds.add(order.getOrderId());
                                }

//                                if (!StringUtil.isEmpty(giftBagName) && !StringUtil.isEmpty(giftBagAmount)) {
//                                    Order order = new Order();
//                                    order.setOrderId("15642358456363");
//                                    order.setMoney(Double.valueOf(giftBagAmount));
//                                    order.setUserMobel("19117681548");
//                                    order.setPayOrderId("fsd5fgsd54gds556");
//                                    order.setName(giftBagName);
//                                    orderMapper.add(order);
//                                    orderIds.add(order.getOrderId());
//                                }

                                if (!CollUtil.isEmpty(orderIds)) {
                                    List<Order> list = orderMapper.getByOrderId(orderIds);
                                    return list.toString();
                                }

                                System.out.println("arguments1 =>>>> " + arguments);
                                return "购买失败，返回订单信息";
                            };

                            ToolProviderResult result = ToolProviderResult.builder()
                                    .add(toolSpecification, toolExecutor)
                                    .build();
                            return result;
                        }

                        // 订单相关
                        if (request.userMessage().singleText().contains("订单列表") || request.userMessage().singleText().contains("历史订单") || request.userMessage().singleText().contains("所有订单")){
                            ToolSpecification toolSpecification = ToolSpecification.builder()
                                    .name("get_assistant")
                                    .description("查询用户的数据")
                                    .build();

                            // 业务逻辑 ToolExecutor
                            ToolExecutor toolExecutor = (toolExecutionRequest, memoryId) -> {
                                List<Order> orders = orderMapper.getAll();
                                return "查询成功，将数据原封不动的返回：" + orders.toString();
                            };

                            System.out.println(toolExecutor);

                            return ToolProviderResult.builder()
                                    .add(toolSpecification, toolExecutor)
                                    .build();
                        }
                        return null;
                    }
                })
                .build();
    }


    /**
     * 数字提取
     * @param chatLanguageModel
     * @return
     */
    @Bean
    public NumberExtractor numberExtractor(ChatLanguageModel chatLanguageModel) {
        return AiServices.create(NumberExtractor.class,chatLanguageModel);
    }


    /**
     * 对象提取
     * @param chatLanguageModel
     * @return
     */
    @Bean
    public UserExtractor personExtractor(ChatLanguageModel chatLanguageModel) {
        return AiServices.create(UserExtractor.class,chatLanguageModel);
    }


}
